export default class Proto2Json {
    public static toJson(jsonobj: any,): string {
        let messages = jsonobj["messages"]
        let msarray: Array<string> = new Array();
        for (let k = 0; k < messages.length; k++) {
            let message = messages[k];
            let str = Proto2Json.messageToJson(message);
            msarray.push(str);
        }
        return msarray.join(",\r\n");
    }
    private static messageToJson(message: any,ischild:boolean=false): string {
        let messArrayObj: Array<any> = new Array();
        let messagename:string=message["name"];
        messagename=messagename.replace(/_/g,".");
        messArrayObj.push(`"${ischild?"message ":""}${messagename}":{`)
        let fields = message["fields"];
        Proto2Json.messageFiledsToString(fields, messArrayObj, message);
        messArrayObj.push("}")
        return messArrayObj.join("\r\n")
    }
    private static messageFiledsToString(fields: Array<any>, messArrayObj: Array<any> , message: any) {
        for (let j = 0; j < fields.length; j++) {
            let field = fields[j];
            let type: Set<string> = new Set();
            type.add("double").add("float").add("int32").add("int64").add("uint32").add("uint64").add("sint32").add("sint64").add("fixed32").add("fixed64").add("sfixed32").add("sfixed64").add("bool").add("string").add("bytes")
            let enu=false;
            if (!type.has(field["type"])) {

                let msg = Proto2Json.findMessage(message, field["type"]);
                if (msg) {
                    let str = Proto2Json.messageToJson(msg,true);
                    messArrayObj.push(str+",");
                    //console.log(str);
                }else {
                    if(Proto2Json.isEnum(message,field["type"])){
                        enu=true;
                    }
                }
            }
            let fieldJson = `"${field["rule"]} ${enu?"int32":field["type"]} ${field["name"]}":${field["id"]}${(j == fields.length - 1) ? "" : ","}`
            messArrayObj.push(fieldJson);
        }
    }
    private static findMessage(message: any, typeName: string) {
        for (let i = 0; i < message["messages"].length; i++) {
            let itemmsg = message["messages"][i]
            if (itemmsg["name"] == typeName) {
                return itemmsg;
            }
        }
        return null;
    }

    private static isEnum(message: any, typeName: string):boolean{
        for (let i=0;i< message["enums"].length;i++){
            let itemmsg = message["enums"][i]
            if (itemmsg["name"] == typeName) {
                return true;
            }
        }
        return false;
    }


}